package com.resou.reader.bookshelf;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewFlipper;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DecodeFormat;
import com.bumptech.glide.request.RequestOptions;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.resou.reader.MainActivity;
import com.resou.reader.R;
import com.resou.reader.ReSouApplication;
import com.resou.reader.activity.freebook.FreeBookActivity;
import com.resou.reader.activity.friendboost.FriendBoostActivity;
import com.resou.reader.api.ApiConstant;
import com.resou.reader.api.entry.BookContentBean;
import com.resou.reader.api.entry.LoginData;
import com.resou.reader.api.entry.LoginResult;
import com.resou.reader.api.entry.ShareTimeBean;
import com.resou.reader.assist.WebActivity;
import com.resou.reader.base.ResouBaseFragment;
import com.resou.reader.bookshelf.adapter.BookShelfAdapter;
import com.resou.reader.bookshelf.bookedit.BookShelfEditActivity;
import com.resou.reader.bookshelf.dialogutil.BookLongPressDialog;
import com.resou.reader.bookshelf.dialogutil.MenuClickDialog;
import com.resou.reader.bookshelf.readhistory.ReadHistoryActivity;
import com.resou.reader.bookshelf.readhistory.datasupport.BookCollection;
import com.resou.reader.bookshelf.readhistory.datasupport.ReaderHistory;
import com.resou.reader.data.bookshelf.model.ScrollNotice;
import com.resou.reader.data.local.LitePalHelper;
import com.resou.reader.data.signin.model.SignStatus;
import com.resou.reader.mine.IView.UserInstance;
import com.resou.reader.mine.listener.LoginListener;
import com.resou.reader.mine.login.LoginFragment;
import com.resou.reader.reader.v.ReaderActivity;
import com.resou.reader.search.search2.Search2Activity;
import com.resou.reader.signin.style1.SignInActivity;
import com.resou.reader.utils.NetworkUtils;
import com.resou.reader.utils.PreferenceUtil;
import com.resou.reader.utils.StatusBarUtil;
import com.resou.reader.utils.TextUtils;
import com.resou.reader.utils.ToastUtil;
import com.resou.reader.utils.ViewSizeUtils;
import com.resou.reader.utils.WXUtils;
import com.resou.reader.utils.eventbus.BookShelfEvent;
import com.resou.reader.utils.eventbus.LoadBookEvent;
import com.resou.reader.utils.eventbus.MessageEvent;
import com.resou.reader.view.CustomLoadMoreView;
import com.resou.reader.view.Loading;
import com.resou.reader.view.RGridLayoutManager;
import com.resou.reader.view.RLinearLayoutManager;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMWeb;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.text.DecimalFormat;
import java.util.Collections;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class HomeBookShelfFragment extends ResouBaseFragment<HomeBookShelfPresenter> implements HomeBookShelfContract.HomeBookShelfView {
    private static final String TAG = "HomeBookShelfFragment";
    private MainActivity mMainActivity;
    public static int mSignStatus;//登陆状态
    private long firstTime = 0;//记录用户首次点击返回键的时间
    private long secondTime = 0;//记录用户首次点击返回键的时间
    private Handler handler = new Handler();
    private boolean isHasBook;
    BookShelfAdapter mAdapter;
    DecimalFormat decimalFormat = new DecimalFormat("#0.00");
    BookCollection bookCo;
    int page = 0;
    final int pagesize = 30;
    View viewHeader;
    View viewGridadd;
    View viewListadd;

    @BindView(R.id.tv_money)
    TextView tvMoney;
    @BindView(R.id.icon_action_search)
    ImageView iconActionSearch;
    @BindView(R.id.icon_record_light)
    ImageView iconRecordLight;
    @BindView(R.id.icon_menu)
    ImageView iconMenu;
    //    @BindView(R.id.tv_recent_reading_title)
    TextView tvRecentReadingTitle;
    //    @BindView(R.id.iv_recent_reading_icon)
    ImageView ivRecentReadingIcon;
    //    @BindView(R.id.tv_recent_reading_des)
    TextView tvRecentReadingDes;
    //    @BindView(R.id.iv_recent _reading_img)
    ImageView ivRecentReadingImg;
    LinearLayout ll_book_cover;
    //    @BindView(R.id.view_flipper)
    ViewFlipper viewFlipper;
    //    @BindView(R.id.ll_sign)
    LinearLayout llSign;
    @BindView(R.id.book_shelf_recycler_view)
    RecyclerView bookShelfRecyclerView;
    //    @BindView(R.id.nested_scroll_view)
//    NestedScrollView nestedScrollView;
    @BindView(R.id.smart_refresh_layout)
    SmartRefreshLayout smartRefreshLayout;
    @BindView(R.id.ll_batch_manage)
    LinearLayout llBatchManage;
    @BindView(R.id.iv_list_icon)
    ImageView ivListIcon;
    @BindView(R.id.tv_list_title)
    TextView tvListTitle;
    @BindView(R.id.ll_list_show)
    LinearLayout llListShow;
    @BindView(R.id.fl_batch_manage)
    FrameLayout flBatchManage;
    @BindView(R.id.rl_book_shelf_toolbar)
    RelativeLayout rl_book_shelf_toolbar;
    List<BookCollection> bookCollectionList = null;
    int pos = 0;

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_home_book_shelf_new;
    }

    @Override
    public void showContent(List<BookCollection> list) {
        if (UserInstance.isLogin()) {
            for (BookCollection bookCollection : list) {
                PreferenceUtil.getInstance(ReSouApplication.getRSApplication()).saveFreeBooks(UserInstance.getLoginData().getId() + "", bookCollection.getBookId());
            }
        }

        if (page == 0) {
            mAdapter.setNewData(list);
            if (0 == mAdapter.getType()) {
                mAdapter.setFooterViewAsFlow(true);
            }
        } else {
            mAdapter.addData(list);
        }
    }

    @Override
    public SmartRefreshLayout getSmartRefreshLayout() {
        return smartRefreshLayout;
    }

    @Override
    public BaseQuickAdapter getAdapter() {
        return mAdapter;
    }

    @Override
    public void deleteItem(String bookID) {
        for (int i = 0; i < mAdapter.getData().size(); i++) {
            if (mAdapter.getData().get(i) instanceof BookCollection) {
                BookCollection book = mAdapter.getData().get(i);
                if ((book.getBookId().equals(bookID))) {
                    mAdapter.getData().remove(i);
                    mAdapter.notifyDataSetChanged();
                }
            }
        }
    }

    @Override
    public Context getViewContext() {
        return getActivity();
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        mMainActivity = (MainActivity) context;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);
    }

    @Override
    public void initData() {
        if (NetworkUtils.isNetworkConnected(mActivity)) {
            mPresenter.updateSignInfo();
            mPresenter.loadRemoteBooks(page, pagesize);
        } else {
            mPresenter.requestPursuitBookList();
        }
    }

    @Override
    protected void initPresenter() {

    }

    @Override
    protected void initView() {
        initHeader();
        rl_book_shelf_toolbar.setBackgroundColor(getResources().getColor(R.color.colorPrimaryDark));
        // 和顶部保持一定的距离
        int height = ViewSizeUtils.getStatusBarHeight(mActivity.getResources()) + mMainActivity.getState();
        LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) rl_book_shelf_toolbar.getLayoutParams();
        layoutParams.setMargins(0, height - 10, 0, 0);
        rl_book_shelf_toolbar.setLayoutParams(layoutParams);

        mPresenter = new HomeBookShelfPresenter(this);

        //设置补贴金额
        try {
            tvMoney.setText(decimalFormat.format(PreferenceUtil.getInstance(getActivity()).getMoney()));
        } catch (Exception e) {
            Log.i(TAG, "initView: " + e.getMessage());
        }
        //注册EventBus
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }

        //设置刷新动画的颜色为红色
        smartRefreshLayout.setPrimaryColorsId(R.color.selector_white_normal_theme_red, android.R.color.white);
        smartRefreshLayout.setEnableLoadMore(false);

        //取消RecyclerView的聚焦，防止在低版本的手机上出现红色区域被挤上去
        bookShelfRecyclerView.setFocusable(false);
        bookShelfRecyclerView.setFocusable(false);

        viewGridadd = getLayoutInflater().inflate(R.layout.recycler_item_add, null);
        viewListadd = getLayoutInflater().inflate(R.layout.recycler_item_add_list, null);
        viewGridadd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (MainActivity.instance != null) {
                    MainActivity.instance.setTabSelection(1);
                }
            }
        });

        viewListadd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (MainActivity.instance != null) {
                    MainActivity.instance.setTabSelection(1);
                }
            }
        });

        //初始化recycleview adapter
        mAdapter = new BookShelfAdapter(R.layout.recycler_item_book_shelf, null);
        mAdapter.setHeaderView(viewHeader, LinearLayout.HORIZONTAL);
        if (PreferenceUtil.getInstance(ReSouApplication.getRSApplication()).getIsListShow()) {
            //列表模式书架
            mAdapter.setType(1);
            bookShelfRecyclerView.setLayoutManager(new RLinearLayoutManager(getViewContext()));
            mAdapter.notifyDataSetChanged();
            mAdapter.addFooterView(viewListadd);
            mAdapter.setHeaderView(viewHeader, LinearLayout.HORIZONTAL);
            mAdapter.notifyDataSetChanged();
        } else {
            //图墙模式书架
            mAdapter.setType(0);
            bookShelfRecyclerView.setLayoutManager(new RGridLayoutManager(getViewContext(), 3));
            mAdapter.setHeaderView(viewHeader, LinearLayout.HORIZONTAL);
            mAdapter.notifyDataSetChanged();
            mAdapter.addFooterView(viewGridadd);
            mAdapter.setFooterViewAsFlow(false);
        }


        bookShelfRecyclerView.setAdapter(mAdapter);
        mAdapter.setLoadMoreView(new CustomLoadMoreView());
        mAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                pos = position;
                bookCollectionList = mAdapter.getData();
                if (mAdapter.getType() == 0 || mAdapter.getType() == 1) {
                    BookCollection tmpBook = mAdapter.getData().get(position);
                    long secondTime = System.currentTimeMillis();
                    if (secondTime - firstTime < 2000) {
                        return;
                    }
                    firstTime = secondTime;
                    mPresenter.updataLookTime(tmpBook);
                    ReaderActivity.startActivity(mMainActivity, tmpBook, true);
                }
            }
        });

        mAdapter.setOnItemChildLongClickListener(new BaseQuickAdapter.OnItemChildLongClickListener() {
            @Override
            public boolean onItemChildLongClick(BaseQuickAdapter adapter, View view, int position) {
                Intent intent = new Intent(getActivity(), BookShelfEditActivity.class);
                intent.putExtra("position", position);
                startActivity(intent);
                return false;
            }
        });


        smartRefreshLayout.setOnRefreshListener(refreshLayout -> {
            page = 0;
            try {
                tvMoney.setText(decimalFormat.format(PreferenceUtil.getInstance(getActivity()).getMoney()));
            } catch (Exception e) {
                Log.i(TAG, "setOnRefreshListener: " + e.getMessage());
            }
            initViewFlipper();
            if (NetworkUtils.isNetworkConnected(mActivity)) {
                mPresenter.loadRemoteBooks(page, pagesize);
            } else {
                page = 0;
                mPresenter.requestPursuitBookList();
                smartRefreshLayout.finishRefresh();
                mAdapter.loadMoreFail();
            }
        });

        mAdapter.setPreLoadNumber(10);
        mAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                page++;
                mPresenter.loadRemoteBooks(page, pagesize);
            }
        }, bookShelfRecyclerView);


        //补贴活动弹框
        if (PreferenceUtil.getInstance(getActivity()).getSubSidyState()) {
            initDialog();
        }

        if (NetworkUtils.isNetworkConnected(mActivity)) {
            //初始化滚动公告栏
            initViewFlipper();
        }
    }

    @Override
    protected void retryRefreshData() {

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 1) {
            if (resultCode == Activity.RESULT_OK) {
                mPresenter.updateSignInfo();
            }
        }
    }

    @Override
    public void showContent() {
    }

    @Override
    public void showProgress() {
    }

    @Override
    public void showError(Throwable throwable) {

    }

    @Override
    public void showEmpty() {

    }

    /**
     * 显示签到状态
     *
     * @param data
     */
    @Override
    public void showSignStatus(SignStatus data) {
        mSignStatus = data.getSignStatus();
        if (mSignStatus == 0) {
            //未签到
//            tvTitle.setText("签到可获得更多热券");
//            iv_Sign.setVisibility(View.VISIBLE);
        } else {
            //签过到
//            tvTitle.setText("今日签到送" + data.getSignVoucher() + "热券");
            if (UserInstance.isLogin()) {
//                iv_Sign.setVisibility(View.GONE);
            } else {
//                iv_Sign.setVisibility(View.VISIBLE);
            }
//            Log.i(TAG, "showSignStatus: " + iv_Sign.getVisibility());
        }
    }


    /**
     * //切换书架图强显示方式
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(BookShelfEvent event) {
        if (PreferenceUtil.getInstance(ReSouApplication.getRSApplication()).getIsListShow()) {
            //列表模式书架
            mAdapter.setType(1);
            bookShelfRecyclerView.setLayoutManager(new RLinearLayoutManager(getViewContext()));
            mAdapter.notifyDataSetChanged();
            mAdapter.removeAllFooterView();
            mAdapter.addFooterView(viewListadd);
        } else {
            //图墙模式书架
            mAdapter.setType(0);
            bookShelfRecyclerView.setLayoutManager(new RGridLayoutManager(getViewContext(), 3));
            mAdapter.onAttachedToRecyclerView(bookShelfRecyclerView);
            mAdapter.notifyDataSetChanged();
            mAdapter.removeAllFooterView();
            mAdapter.addFooterView(viewGridadd);
            mAdapter.setFooterViewAsFlow(false);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MessageEvent event) {
        Loading.getInstance().dismiss();
        //清除待删除列表
        mPresenter.updateSignInfo();
        viewFlipper.removeAllViews();
        //重新加载书架翻页面板
        mPresenter.getScrollBulletinBoard(UserInstance.getToken());
    }

//    public String getFreeBooks() {
//        StringBuilder buffer = new StringBuilder();
//        for (int i = 0; i < mAdapter.getData().size(); i++) {
//            Object o = mAdapter.getData().get(i);
//            if (o != null) {
//                BookCollection book = (BookCollection) o;
//                int freeStatus = book.getFreeStatus();
//                if (freeStatus == 0) {
//                    buffer.append(book.getBookId()).append("_").append(0);
//                } else {
//                    buffer.append(book.getBookId()).append("_").append(1);
//                }
//                if (i != mAdapter.getData().size() - 2) {
//                    buffer.append(",");
//                }
//            }
//        }
//        Log.i(TAG, "OkHttp: -->" + buffer.toString());
//        return buffer.toString();
//    }

    /**
     * 首次登录成功同步本地书架到服务器
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(Message event) {
        //重新加载书架书本
        Log.i(TAG, "onMessageEvent: 同步书籍");
        page = 0;
        mPresenter.synchronizeBooks(TextUtils.getFreeBooks(mAdapter.getData()));
        mPresenter.quearCover();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(LoadBookEvent event) {
        if (!event.isRefresh()) {
            Log.i(TAG, "onMessageEvent: 不刷新");
            return;
        }
        if (NetworkUtils.isNetworkConnected(mActivity)) {
            page = 0;
            Log.i(TAG, "onMessageEvent: 刷新");
            mPresenter.loadRemoteBooks(page, pagesize);
            mPresenter.quearCover();
        } else {
            mPresenter.requestPursuitBookList();
        }
    }

    /**
     * 书架点击后的无感知更新书籍顺序
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(BookCollection event) {
//        Log.i(TAG, "onMessageEvent: 同步书籍" + event);

        if (!TextUtils.isEmpty(event.getBookId())) {
            Log.i(TAG, "onMessageEvent: 上传五本免费籍");
            //重新加载书架书本
            mPresenter.synchronizeBooks(TextUtils.getFreeBooks(LitePalHelper.loadShelfBooks()));
        } else {
            Log.i(TAG, "onMessageEvent: 同步书架");
            Log.i(TAG, "onItemChildClick: " + event.getName());
            Log.i(TAG, "isRemove: " + event.isRemove());
            Log.i(TAG, "onMessageEvent: " + event.getHistoryChapterName());
            if (1 != event.isRemove() || bookCollectionList == null) {
                return;
            }
            if (bookCollectionList.get(0).getBookId().equals(event.getBookId())) {
                Log.i(TAG, "onMessageEvent: 第一项" + event.getHistoryChapterName());
                bookCollectionList.remove(0);
                bookCollectionList.add(0, event);
                mAdapter.onAttachedToRecyclerView(bookShelfRecyclerView);
                mAdapter.setNewData(bookCollectionList);
            } else {
                Log.i(TAG, "onMessageEvent: 第非项" + event.getHistoryChapterName());
                bookCollectionList.remove(pos);
                bookCollectionList.add(0, event);
                mAdapter.onAttachedToRecyclerView(bookShelfRecyclerView);
                mAdapter.setNewData(bookCollectionList);
            }
        }
        mPresenter.quearCover();
//    }

    }


    /**
     * 设置滚动条信息
     *
     * @param scrollBoardInfo
     */
    @Override
    public void setScrollBoardInfo(List<ScrollNotice> scrollBoardInfo) {
        Log.e(TAG, scrollBoardInfo.toString());
        for (ScrollNotice boardInfo : scrollBoardInfo) {
            View item = LayoutInflater.from(mActivity).inflate(R.layout.broad_cast_layout, viewFlipper, false);
            ((TextView) item.findViewById(R.id.broadcast_text)).setText(boardInfo.getNotice() + "");
            /**
             * 0普通公告 进入签到页面
             * 1：立即参加
             * 2：分享
             */
            Log.i(TAG, "setScrollBoardInfo: " + boardInfo.getType());
            if (boardInfo.getType() == 0) {
                item.findViewById(R.id.bord_cast_Onclick).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        /**
                         * 判断用户是否登录如果登录 进入公告相关逻辑
                         * 否则弹出登录框让用户登录
                         */
                        WebActivity.startActivity(getActivity(), ApiConstant.VIPDUIBA + UserInstance.getToken(), "签到");
                    }
                });
            } else if (boardInfo.getType() == 1) {
                item.findViewById(R.id.bord_cast_Onclick).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        /**
                         * 判断用户是否登录如果登录 进入公告相关逻辑
                         * 否则弹出登录框让用户登录
                         */
                        FreeBookActivity.start(mActivity);
                    }
                });
            } else if (boardInfo.getType() == 2) {
                item.findViewById(R.id.bord_cast_Onclick).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        /**
                         * 进入公告相关逻辑
                         */
                        FriendBoostActivity.start(mActivity);
                    }
                });
            }
            viewFlipper.addView(item);
        }
        viewFlipper.startFlipping();
    }

    /**
     * 停止刷新
     */
    @Override
    public void finishRefresh() {
        if (smartRefreshLayout != null) {
            smartRefreshLayout.finishRefresh();
        }
    }

    /**
     * 设置书封信息
     */
    @Override
    public void setBookCover(BookCollection books) {
        try {
            tvMoney.setText(decimalFormat.format(PreferenceUtil.getInstance(getActivity()).getMoney()));
        } catch (Exception e) {
            Log.i(TAG, "setBookCover: " + e.getMessage());
        }
        if (books != null) {
            bookCo = books;
            ReaderHistory readerHistory = LitePalHelper.loadReadHistory(books.getBookId());
            if (readerHistory != null) {
                bookCo.setPageIndex(readerHistory.getPageIndex());
                bookCo.setCharIndex(readerHistory.getCharIndex());
                bookCo.setChapterIndex(readerHistory.getChapterIndex());
                bookCo.setHistoryChapterId(readerHistory.getHistoryChapterId());
            }
            tvRecentReadingTitle.setText(bookCo.getName());
            tvRecentReadingDes.setText("阅读到：" + bookCo.getHistoryChapterName());
            ivRecentReadingIcon.setImageResource(R.mipmap.icon_recent_reading);
            if (bookCo.getPicUrl() != null) {
                Glide.with(getViewContext()).setDefaultRequestOptions(new RequestOptions().format(DecodeFormat.PREFER_RGB_565)).load(bookCo.getPicUrl()).into(ivRecentReadingImg);
            }
            isHasBook = true;
        } else {
            tvRecentReadingTitle.setText("没有一种苦恼是读书所不能驱散的。");
            tvRecentReadingDes.setText("一孟德斯鸠");
            ivRecentReadingImg.setImageResource(R.mipmap.icon_default_book);
            ivRecentReadingIcon.setImageResource(R.mipmap.icon_recent_reading1);
            isHasBook = false;
        }

    }

    /**
     * 初始化头部信息
     */
    private void initHeader() {
        viewHeader = LayoutInflater.from(getActivity()).inflate(R.layout.fragment_home_layout_header, null);
        //
        viewHeader.findViewById(R.id.rl_block).setBackgroundColor(getResources().getColor(R.color.colorPrimaryDark));
        ll_book_cover = viewHeader.findViewById(R.id.ll_book_cover);
        tvRecentReadingTitle = viewHeader.findViewById(R.id.tv_recent_reading_title);
        ivRecentReadingIcon = viewHeader.findViewById(R.id.iv_recent_reading_icon);
        tvRecentReadingDes = viewHeader.findViewById(R.id.tv_recent_reading_des);
        ivRecentReadingImg = viewHeader.findViewById(R.id.iv_recent_reading_img);
        viewFlipper = (ViewFlipper) viewHeader.findViewById(R.id.view_flipper);
        llSign = viewHeader.findViewById(R.id.ll_sign);
        ll_book_cover.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isHasBook) {
                    long secondTime = System.currentTimeMillis();
                    if (secondTime - firstTime < 2000) {
                        return;
                    }
                    firstTime = secondTime;
                    mPresenter.updataLookTime(bookCo);
                    ReaderActivity.startActivity(mMainActivity, bookCo, false);
                } else {
                    mMainActivity.setTabSelection(1);
                }
            }
        });
        llSign.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                WebActivity.startActivity(getActivity(), ApiConstant.VIPDUIBA + UserInstance.getToken(), "签到");
            }
        });
    }


    /**
     * 初始化滚动公告栏
     */
    private void initViewFlipper() {
        if (NetworkUtils.isNetworkConnected(mActivity)) {
            mPresenter.getScrollBulletinBoard(UserInstance.getToken());
        } else {
            showDefaultViewFlipper();
        }
    }

    /**
     * 设置默认滚动公告栏
     */
    private void showDefaultViewFlipper() {
        for (int i = 0; i < 2; i++) {
            View item = LayoutInflater.from(mMainActivity).inflate(R.layout.broad_cast_layout, viewFlipper, false);
            ((TextView) item.findViewById(R.id.broadcast_text)).setText("签到领取更多福利");
            viewFlipper.addView(item);
        }
        if (viewFlipper.isFlipping()) {
            return;
        }
        viewFlipper.startFlipping();
    }

    /**
     * 显示补贴活动弹框
     */
    private void initDialog() {
        View view = LayoutInflater.from(getActivity()).inflate(R.layout.subsidy_layout, null);
        ImageView mView = view.findViewById(R.id.mView);
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setCancelable(false);
        builder.setView(view);
        AlertDialog alertDialog = builder.create();
        alertDialog.getWindow().setBackgroundDrawableResource(R.color.transparent);
        mView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (alertDialog.isShowing()) {
                    alertDialog.dismiss();
                }
                PreferenceUtil.getInstance(getContext()).saveSubSidyState(false);
            }
        });
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        if (!getActivity().isFinishing() && alertDialog != null) {
            alertDialog.show();
        }
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        if (!hidden) {
            //显示时
            System.out.println("class:" + this.getClass().getName() + "\thidden:" + hidden);
            StatusBarUtil.setStatusBarColor(getActivity(), getResources().getColor(R.color.colorAccent));
        }
    }

    @OnClick({R.id.icon_action_search, R.id.icon_record_light, R.id.icon_menu, R.id.ll_batch_manage, R.id.ll_list_show})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            //搜索
            case R.id.icon_action_search:
                Search2Activity.start(mActivity);
                break;
            //阅读足迹
            case R.id.icon_record_light:
                ReadHistoryActivity.start(mActivity);
                break;
            //菜单
            case R.id.icon_menu:
                MenuClickDialog menuClickDialog = new MenuClickDialog();
                menuClickDialog.show(getChildFragmentManager(), "");
                break;
        }
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        assert rootView != null;
        unbinder = ButterKnife.bind(this, rootView);
        StatusBarUtil.setStatusBarColor(getActivity(), getResources().getColor(R.color.colorAccent));
        return rootView;
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
        handler.removeCallbacksAndMessages(null);
    }


}
